package com.kaba.xtzhgl.service.serviceImpl;


import com.kaba.bean.SysMenu;
import com.kaba.bean.SysUser;
import com.kaba.xtzhgl.service.SysMenuService;
import com.kaba.xtzhgl.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public  class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("-------------------开始认证-----");
        //1.查询用户账号对应的用户信息
        System.out.println(username);
        SysUser sysUser=sysUserService.queryByName(username);
        if (sysUser ==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //2. 查询用户id对应的角色下面所有的权限码
        List<SysMenu> permissonCodeList =sysMenuService.queryByname(sysUser.getUserId());

        //将权限码循环填充在认证对象GrantedAuthority中
        List<GrantedAuthority> authorities=new ArrayList<>();
        // 声明用户授权
        for (SysMenu sysMenu : permissonCodeList) {
            authorities.add(new SimpleGrantedAuthority(sysMenu.getPerms()));
            System.out.println(sysMenu.getPerms());
        }
        redisTemplate.opsForValue().set("kabam",permissonCodeList);
        //3.返回一个user对象（填充用户名，密码，权限码）
        return new User(sysUser.getUserName(),sysUser.getPassword(),authorities);

    }
}
